package com.zkw.group.controller;

import com.alibaba.fastjson.JSON;
import com.zkw.group.entity.CourseBook;
import com.zkw.group.entity.QueryInfo;
import com.zkw.group.service.CourseBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@Api(description = "管理课程有关参考书目信息")
@CrossOrigin
@RestController
@RequestMapping("/CourseBooks")
public class CourseBookController {

    @Autowired
    private CourseBookService courseBookService;

    @ApiOperation(value = "分页查询课程有关参考书目信息")
    @GetMapping("/AllCourseBook")
    public String getAllCourseBookList(QueryInfo queryInfo) {
        int numbers = courseBookService.getCourseBookCounts(queryInfo.getQuery(),queryInfo.getRole());
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<CourseBook> courseBooks = courseBookService.getAllCourseBookList(queryInfo.getQuery(),queryInfo.getRole(),pageStart,queryInfo.getPageSize());
        HashMap<String, Object> res = new HashMap<>();
        res.put("numbers",numbers);
        res.put("data",courseBooks);
        return JSON.toJSONString(res);
    }

    @ApiOperation(value = "添加课程有关参考书目信息")
    @PostMapping("/CourseBook")
    public String addCourseBook(@RequestBody CourseBook courseBook) {
        int result;
        try{
            result = courseBookService.addCourseBook(courseBook);
        }
        catch(Exception e) {
            result = 0;
        }
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }

    @ApiOperation(value = "删除指定课程有关参考书目信息")
    @DeleteMapping("/CourseBook")
    public String deleteCourseBook(String bookname) {
        int result = courseBookService.deleteCourseBook(bookname);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }

    @ApiOperation(value = "查询指定有关参考书目信息")
    @GetMapping("/CourseBookMessage")
    public String getUpdateCourseBook(String courseid,String bookname) {
        CourseBook updateCourseBook = courseBookService.getUpdateCourseBook(courseid,bookname);
        String users_json = JSON.toJSONString(updateCourseBook);
        return users_json;
    }

    @ApiOperation(value = "更新指定有关参考书目信息")
    @PutMapping("/CourseBook")
    public String updateCourseBook(@RequestBody CourseBook courseBook) {
        int result = courseBookService.updateCourseBook(courseBook);
        if (result >= 1) {
            return "success";
        } else {
            return "error";
        }
    }

}
